package com.caits.lbs.framework.action;

/*
 * Date: 2012-10-18
 * author: Fsr  
 *
 */

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import com.caits.lbs.framework.Constants;
import com.caits.lbs.framework.services.memcache.IMemcacheService;
import com.caits.lbs.framework.utils.FileUtils;
import com.caits.lbs.framework.utils.HttpUtils;
import com.caits.lbs.framework.utils.ServletUtils;
import com.caits.lbs.framework.utils.StringUtils;

/**
 * <p>
 * BaseFilter
 * </p>
 * <p>
 * 基本的http接入过滤器
 * </p>
 * @author 周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhouhuabin</td>
 *          <td>2014年11月19日 上午11:29:51</td>
 *          </tr>
 *          <tr>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          </tr>
 *          </table>
 */
public abstract class BaseFilter extends OncePerRequestFilter {
	/** 变量:TODO,类型:Logger */
	protected Logger LOG = Constants.LOGSLF;

	/** 缓存访问接口 */
	@Autowired
	private IMemcacheService client;
	
	/** 变量:忽略掉的过滤串,类型:String */
	private String ignoreAction = "preorder";
	/** 变量:本地缓存数据,类型:Map<String,Object> */
	
	/** 变量:默认是否过滤,类型:boolean */
	private boolean enableFilter = false;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String uri = ServletUtils.getUri(request);
		LOG.info("收到请求 url:{}", uri + "?" + ServletUtils.getParameterValues(request) + ",client=" + HttpUtils.getClientIpAddr(request));
		if (enableFilter  && uri.contains(ignoreAction)) {
			if(!filterBusiness(request,response)){
				return;
			}
		}
		filterChain.doFilter(request, response);
	}

	/**
	 * FIXME 
	 * @param request
	 * @param response
	 * @return boolean
	 */
	protected abstract boolean filterBusiness(HttpServletRequest request, HttpServletResponse response);
		

	/**
	 * 构建通用返回<tt>map</tt>对象
	 * @param resultCode	响应代码
	 * @param	msg			响应的提示消息,<tt>null</tt>时则用<strong>成功</strong>代替
	 * @param	data		返回的数据对象
	 * @return Map<String,Object>
	 */
	protected Map<String,Object> buildCommonReturnMap(String resultCode,String msg,Object data){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put(Constants.RESULTCODE,resultCode);
		map.put(Constants.RESULTMSG,StringUtils.null2default(msg,"成功"));
		if(data!=null){
			map.put(Constants.RESULTDATA,data);
		}
		return map;
	}
	/**
	 * 向http响应输出数据 
	 * @param resultCode
	 * @param response
	 * @param returnValue
	 * @param format
	 * @param serviceName
	 */
	protected void fileFormation(String resultCode, HttpServletResponse response, String returnValue,
			String format, String serviceName) {
		
		format = StringUtils.null2default(format, FileUtils.CONST_DEFAULT_CHARSET);;
		// boolean isZip = isZip(zip);
		OutputStream os = null;
		try {
			response.setCharacterEncoding(FileUtils.CONST_DEFAULT_CHARSET);
			response.addHeader(Constants.RESULTCODE, Constants.RESULTCODE_SUCCESS);
			byte[] returnData = returnValue.getBytes(FileUtils.CONST_DEFAULT_CHARSET);
			int length = returnData.length;
			if (Constants.RESULT_TYPE_XML.equals(format)) {
				response.setContentType(Constants.ContentTypeXmlUtf8);
			} else if (Constants.RESULT_TYPE_JSON.equals(format)) {
				response.setContentType(Constants.ContentTypeJsonUtf8);
			}
			// --------------如果下个版本增加别的格式数据在从这扩展----------------
			os = response.getOutputStream();
			if (os != null) {
				os.write(returnData);
			}
			LOG.info("{}接口调用结果{},返回数据length={}bytes!", new Object[]{serviceName,resultCode,Integer.toString(length)});
		} catch (IOException e) {
			LOG.error("返回客户端数据异常,msg="+e.getLocalizedMessage(), e);
			response.setHeader(Constants.RESULTCODE, Constants.RESULTCODE_SERVERERROR);
			LOG.error("{} resultCode:{}", serviceName, Constants.RESULTCODE_SERVERERROR);
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				LOG.error("关闭连接出错,msg="+e.getLocalizedMessage());
			}
		}

	}



	/**
	 * 获取属性 client的值
	 * @return the client : IMemcacheService
	 */
	public IMemcacheService getClient() {
		return client;
	}

	/**
	 * 设置属性client的值，参数类型IMemcacheService
	 * @param client the client to set
	 */
	public void setClient(IMemcacheService client) {
		this.client = client;
	}

	/**
	 * 获取属性 ignoreAction的值
	 * @return the ignoreAction : String
	 */
	public String getIgnoreAction() {
		return ignoreAction;
	}

	/**
	 * 设置属性ignoreAction的值，参数类型String
	 * @param ignoreAction the ignoreAction to set
	 */
	public void setIgnoreAction(String ignoreAction) {
		this.ignoreAction = ignoreAction;
	}

	/**
	 * 获取属性 enableFilter的值
	 * @return the enableFilter : boolean
	 */
	public boolean isEnableFilter() {
		return enableFilter;
	}

	/**
	 * 设置属性enableFilter的值，参数类型boolean
	 * @param enableFilter the enableFilter to set
	 */
	public void setEnableFilter(boolean enableFilter) {
		this.enableFilter = enableFilter;
	}

	/** (non-Javadoc) 由于filter是容器创建的，需要手动接入spring容器
	 * @see org.springframework.web.filter.GenericFilterBean#initFilterBean()
	 */
	@Override
	protected void initFilterBean() throws ServletException {
		super.initFilterBean();
//		client = (IMemcacheService) Constants.getBean("cacheServer");
//		String filter = (String)commonProperties.get("enableFilter");
//		enableFilter = Boolean.parseBoolean(filter);
	}

}
